﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using TrackIT.Common.Factories;

namespace TrackIT.Common.Repositories
{
    public class FileAccessRepository : IFileAccessRepository
    {
        private readonly IWorkStreamFactory _workStreamFactory;

        public FileAccessRepository(IWorkStreamFactory workStreamFactory)
        {
            _workStreamFactory = workStreamFactory;
        }

        public void Save(List<string> items, string filename)
        {
            if (File.Exists(filename))
                File.Delete(filename);

            using (Stream stream = _workStreamFactory.CreateStream(filename))
            using (TextWriter writer = new StreamWriter(stream))
            {
                foreach (string item in items)
                {
                    writer.WriteLine(item);
                }
            }
        }

        public IEnumerable<string> Load(string filename)
        {
            using (Stream stream = _workStreamFactory.CreateStream(filename))
            {
                TextReader reader = new StreamReader(stream);

                IEnumerable<string> lines = reader.ReadToEnd()
                    .Split('\n', '\r')
                    .Where(l => !string.IsNullOrWhiteSpace(l));

                return lines.AsEnumerable();
            }
        }
    }
}